using DocumentCreationSystem.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace DocumentCreationSystem;

/// <summary>
/// AI工具系统测试程序
/// </summary>
public class TestAITools
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine("=== AI工具系统测试 ===");
        
        try
        {
            // 创建服务容器
            var host = CreateHostBuilder(args).Build();
            
            // 启动服务
            await host.StartAsync();
            
            // 获取AI工具服务
            var aiToolsService = host.Services.GetRequiredService<IAIToolsService>();
            var logger = host.Services.GetRequiredService<ILogger<TestAITools>>();
            
            logger.LogInformation("开始测试AI工具系统...");
            
            // 测试获取工具列表
            await TestGetTools(aiToolsService, logger);
            
            // 测试搜索工具
            await TestSearchTools(aiToolsService, logger);
            
            // 测试工具执行
            await TestToolExecution(aiToolsService, logger);
            
            // 测试工具统计
            await TestToolStatistics(aiToolsService, logger);
            
            Console.WriteLine("\n✅ 所有测试通过！AI工具系统运行正常。");
            
            await host.StopAsync();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"\n❌ 测试失败: {ex.Message}");
            Console.WriteLine($"详细错误: {ex}");
        }
        
        Console.WriteLine("\n按任意键退出...");
        Console.ReadKey();
    }
    
    private static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            })
            .ConfigureServices((context, services) =>
            {
                // 注册基本服务
                services.AddSingleton<IDataStorageService, JsonDataStorageService>();
                services.AddScoped<IProjectService, ProjectService>();
                services.AddScoped<IDocumentService, DocumentService>();
                services.AddSingleton<IThinkingChainService, ThinkingChainService>();
                services.AddSingleton<IAIService>(provider =>
                    new AIServiceManager(
                        provider.GetRequiredService<IConfiguration>(),
                        provider.GetRequiredService<ILogger<AIServiceManager>>(),
                        provider.GetRequiredService<IThinkingChainService>(),
                        provider));
                services.AddScoped<IProjectToolsService, ProjectToolsService>();
                services.AddScoped<IAIToolsService, AIToolsService>();
                services.AddScoped<IVectorService, BGEEmbeddingService>();
                services.AddHttpClient();
                
                // 配置日志
                services.AddLogging(builder =>
                {
                    builder.AddConsole();
                    builder.SetMinimumLevel(LogLevel.Information);
                });
            });
    
    private static async Task TestGetTools(IAIToolsService aiToolsService, ILogger logger)
    {
        Console.WriteLine("\n📋 测试获取工具列表...");
        
        var tools = await aiToolsService.GetAvailableToolsAsync();
        Console.WriteLine($"   找到 {tools.Count} 个可用工具");
        
        foreach (var tool in tools.Take(5))
        {
            Console.WriteLine($"   - {tool.Name} ({tool.Category})");
        }
        
        if (tools.Count > 5)
        {
            Console.WriteLine($"   ... 还有 {tools.Count - 5} 个工具");
        }
    }
    
    private static async Task TestSearchTools(IAIToolsService aiToolsService, ILogger logger)
    {
        Console.WriteLine("\n🔍 测试搜索工具...");
        
        var searchResults = await aiToolsService.SearchToolsAsync("文件");
        Console.WriteLine($"   搜索'文件'找到 {searchResults.Count} 个工具");
        
        foreach (var tool in searchResults.Take(3))
        {
            Console.WriteLine($"   - {tool.Name}: {tool.Description}");
        }
    }
    
    private static async Task TestToolExecution(IAIToolsService aiToolsService, ILogger logger)
    {
        Console.WriteLine("\n⚡ 测试工具执行...");
        
        // 测试目录浏览工具
        var parameters = new Dictionary<string, object>
        {
            ["path"] = ".",
            ["recursive"] = false,
            ["showHidden"] = false
        };
        
        var result = await aiToolsService.ExecuteToolAsync("list-dir", parameters);
        
        if (result.IsSuccess)
        {
            Console.WriteLine($"   ✅ 目录浏览工具执行成功 ({result.ExecutionTimeMs}ms)");
            if (result.Data.ContainsKey("fileCount"))
            {
                Console.WriteLine($"   📁 找到 {result.Data["fileCount"]} 个文件");
            }
        }
        else
        {
            Console.WriteLine($"   ❌ 目录浏览工具执行失败: {result.ErrorDetails}");
        }
    }
    
    private static async Task TestToolStatistics(IAIToolsService aiToolsService, ILogger logger)
    {
        Console.WriteLine("\n📊 测试工具统计...");
        
        var statistics = await aiToolsService.GetToolStatisticsAsync();
        
        Console.WriteLine($"   总工具数: {statistics.TotalTools}");
        Console.WriteLine($"   启用工具: {statistics.EnabledTools}");
        Console.WriteLine($"   使用次数: {statistics.TotalUsageCount}");
        Console.WriteLine($"   成功率: {statistics.AverageSuccessRate:F1}%");
        
        if (statistics.CategoryCounts.Any())
        {
            Console.WriteLine("   工具类别分布:");
            foreach (var category in statistics.CategoryCounts)
            {
                Console.WriteLine($"     - {category.Key}: {category.Value} 个");
            }
        }
    }
}
